package com.bysj.studentsystem.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.bysj.studentsystem.dao.SysUserDao;
import com.bysj.studentsystem.domain.LoginUser;
import com.bysj.studentsystem.entity.SysUser;
import org.assertj.core.util.Lists;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;

/**
 * @ClassName UserDetailsServiceImpl
 * @Description:
 * @Author: xubao@wair.ac.cn
 * @Date: 2024/3/9 22:07
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private SysUserDao sysUserDao;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 查询用户信息
        LambdaQueryWrapper<SysUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysUser::getUsername, username);
        SysUser user = sysUserDao.selectOne(queryWrapper);
        // 如果没有查询到用户就抛出异常
        if (Objects.isNull(user)){
            throw new RuntimeException("用户名或者密码错误");
        }
        // 查询用户对应权限信息
        List<String> permissions = Lists.newArrayList(user.getRoles().split(","));

        // 把用户信息封装成UserDetails返回
        return new LoginUser(user, permissions);
    }

    /**
     * 获取当前用户信息
     * @return
     */
    public SysUser getCurrentUser() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        // 获取用户信息
        return loginUser.getSysUser();
    }

    /**
     * 获取当前用户ID
     * @return
     */
    public Integer getCurrentUserId(){
        return getCurrentUser().getId();
    }

    public String getCurrentUserRoleId(){
        return getCurrentUser().getRoles();
    }

}
